﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFServices.Commands;
using WPFServices.Models.Domain;
using WPFServices.Services.DomainService.ProductPlaninfo;
using WPFServices.Views.DomainViews.ProductPlaninfo;

namespace WPFServices.ViewModels.DomainViewModel.ProductPlaninfo
{
    public class ProductPlanViewModel:BaseViewModel
    {
        private readonly ProductPlanService _productPlanService;
        private ObservableCollection<ProductPlanDto> _productPlans;
        private ProductPlanDto _selectedProductPlan; // 当前选中的生产计划
        private bool _isLoading; // 数据加载状态
        private string _searchPlanId; // 搜索计划编号
        private string _searchPlanName; // 搜索计划名称
        private string _searchProductName; // 搜索产品名称
        private int _currentPage = 1; // 当前页码
        private int _pageSize = 10; // 每页大小
        private int _totalCount; // 总记录数
        private int _totalPages; // 总页数
        public ProductPlanViewModel()
        {
            _productPlanService = new ProductPlanService();
            _productPlans = new ObservableCollection<ProductPlanDto>();
            LoadDataCommand = new RelayCommand(async _ => await LoadProductPlanAsync());
            SearchCommand = new RelayCommand(async _ => await SearchProductPlanAsync());
            FirstPageCommand = new RelayCommand(_ => GoToFirstPage(), _ => CurrentPage > 1);
            PreviousPageCommand = new RelayCommand(_ => GoToPreviousPage(), _ => CurrentPage > 1);
            NextPageCommand = new RelayCommand(_ => GoToNextPage(), _ => CurrentPage < TotalPages);
            LastPageCommand = new RelayCommand(_ => GoToLastPage(), _ => CurrentPage < TotalPages);
            AddProductPlanCommand = new RelayCommand(_ => AddProductPlan());
            DismantleProductPlanCommand = new RelayCommand(async parameter => await DismantleProductPlanAsync(parameter), _ => CanDismantle());

            _ = LoadProductPlanAsync();
        }

        #region 属性
        // 用于UI绑定的数据属性，通过SetProperty实现变更通知。
        public ObservableCollection<ProductPlanDto> ProductPlans
        {
            get => _productPlans;
            set => SetProperty(ref _productPlans, value);
        }

        public ProductPlanDto SelectedProductPlan
        {
            get => _selectedProductPlan;
            set => SetProperty(ref _selectedProductPlan, value);
        }

        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        public string SearchPlanId
        {
            get => _searchPlanId;
            set => SetProperty(ref _searchPlanId, value);
        }

        public string SearchPlanName
        {
            get => _searchPlanName;
            set => SetProperty(ref _searchPlanName, value);
        }

        public string SearchProductName
        {
            get => _searchProductName;
            set => SetProperty(ref _searchProductName, value);
        }

        public int CurrentPage
        {
            get => _currentPage;
            set => SetProperty(ref _currentPage, value);
        }

        public int PageSize
        {
            get => _pageSize;
            set => SetProperty(ref _pageSize, value);
        }

        public int TotalCount
        {
            get => _totalCount;
            set => SetProperty(ref _totalCount, value);
        }

        public int TotalPages
        {
            get => _totalPages;
            set => SetProperty(ref _totalPages, value);
        }

        private async void AddProductPlan()
        {
            try
            {
                var addProductPlanWindow = new AddProductPlan();
                addProductPlanWindow.Owner = System.Windows.Application.Current.MainWindow;

                if (addProductPlanWindow.ShowDialog() == true)
                {
                    await SearchProductPlanAsync(); // 刷新列表
                }
            }
            catch (System.Exception ex)
            {
                System.Windows.MessageBox.Show($"打开新增生产计划窗口失败: {ex.Message}", "错误",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }
        #endregion

        #region 命令
        // 用于UI绑定和触发ViewModel操作的命令。
        public RelayCommand LoadDataCommand { get; }
        public RelayCommand SearchCommand { get; }
        public RelayCommand FirstPageCommand { get; }
        public RelayCommand PreviousPageCommand { get; }
        public RelayCommand NextPageCommand { get; }
        public RelayCommand LastPageCommand { get; }
        public RelayCommand AddProductPlanCommand { get; }
        public RelayCommand DismantleProductPlanCommand { get; }
        #endregion

        #region 方法
        // 加载生产计划数据，重置到第一页并触发搜索。
        private async Task LoadProductPlanAsync()
        {
            CurrentPage = 1;
            SearchPlanId = string.Empty;
            SearchPlanName = string.Empty;
            SearchProductName = string.Empty;
            await SearchProductPlanAsync();
        }

        // 异步搜索生产计划数据，并更新分页信息。
        private async Task SearchProductPlanAsync()
        {
            try
            {
                IsLoading = true;
                System.Diagnostics.Debug.WriteLine("开始搜索生产计划数据...");
                
                var searchDto = new SearchProductPlanDto
                {
                    Plan_Id = SearchPlanId,
                    Plan_Name = SearchPlanName,
                    ProductName = SearchProductName,
                    FromType = 0, // 设置默认值
                    Status = 0,   // 设置默认值
                    PageIndex = CurrentPage,
                    PageSize = PageSize
                };

                System.Diagnostics.Debug.WriteLine($"搜索参数: Plan_Id={searchDto.Plan_Id}, Plan_Name={searchDto.Plan_Name}, ProductName={searchDto.ProductName}, PageIndex={searchDto.PageIndex}, PageSize={searchDto.PageSize}");

                var result = await _productPlanService.SearchProductPlanAsync(searchDto);

                ProductPlans.Clear();
                System.Diagnostics.Debug.WriteLine($"清空数据集合，开始添加数据...");
                
                if (result.Data != null)
                {
                    System.Diagnostics.Debug.WriteLine($"找到 {result.Data.Count} 条数据");
                                         foreach (var productPlan in result.Data)
                     {
                         ProductPlans.Add(productPlan);
                         System.Diagnostics.Debug.WriteLine($"添加数据: ID={productPlan.Id}, Plan_Id={productPlan.Plan_Id}, Plan_Name={productPlan.Plan_Name}");
                     }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("API返回的数据为null");
                }
                
                TotalCount = result.TotalCount;
                TotalPages = result.TotalPage;
                System.Diagnostics.Debug.WriteLine($"设置分页信息: TotalCount={TotalCount}, TotalPages={TotalPages}");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"搜索生产计划数据时发生异常: {ex.Message}");
                System.Windows.MessageBox.Show($"获取生产计划数据失败: {ex.Message}", "错误");
            }
            finally
            {
                IsLoading = false;
                System.Diagnostics.Debug.WriteLine("搜索完成，设置IsLoading=false");
            }
        }

        // 跳转到第一页。
        private void GoToFirstPage()
        {
            CurrentPage = 1;
            _ = SearchProductPlanAsync();
        }

        // 跳转到上一页。
        private void GoToPreviousPage()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                _ = SearchProductPlanAsync();
            }
        }

        // 跳转到下一页。
        private void GoToNextPage()
        {
            if (CurrentPage < TotalPages)
            {
                CurrentPage++;
                _ = SearchProductPlanAsync();
            }
        }

        // 跳转到最后一页。
        private void GoToLastPage()
        {
            CurrentPage = TotalPages;
            _ = SearchProductPlanAsync();
        }

        /// <summary>
        /// 检查是否可以分解生产计划
        /// </summary>
        private bool CanDismantle()
        {
            return SelectedProductPlan != null && SelectedProductPlan.Status == 1; // 只有状态为1（未分解）的才能分解
        }

        /// <summary>
        /// 分解生产计划
        /// </summary>
        private async Task DismantleProductPlanAsync(object parameter)
        {
            try
            {
                ProductPlanDto productPlan = null;
                
                // 如果参数是ProductPlanDto，直接使用；否则使用选中的生产计划
                if (parameter is ProductPlanDto plan)
                {
                    productPlan = plan;
                }
                else
                {
                    productPlan = SelectedProductPlan;
                }

                if (productPlan == null)
                {
                    System.Windows.MessageBox.Show("请先选择要分解的生产计划", "提示", 
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                    return;
                }

                                 if (productPlan.Status != 1)
                 {
                     System.Windows.MessageBox.Show("只有未分解状态的生产计划才能进行分解操作", "提示", 
                         System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                     return;
                 }

                 // 检查生产计划数据的完整性
                 if (string.IsNullOrEmpty(productPlan.Plan_Id) || string.IsNullOrEmpty(productPlan.Plan_Name))
                 {
                     System.Windows.MessageBox.Show("生产计划数据不完整，无法进行分解操作", "提示", 
                         System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                     return;
                 }

                                   System.Diagnostics.Debug.WriteLine($"准备分解生产计划: ID={productPlan.Id}, Plan_Id={productPlan.Plan_Id}, Plan_Name={productPlan.Plan_Name}");
                  
                  // 检查ID是否有效
                  if (productPlan.Id <= 0)
                  {
                      System.Windows.MessageBox.Show("生产计划ID无效，无法进行分解操作", "错误", 
                          System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                      return;
                  }

                                 // 确认分解操作
                 var result = System.Windows.MessageBox.Show(
                     $"确定要分解生产计划 \"{productPlan.Plan_Name}\" (ID: {productPlan.Id}) 吗？\n分解后将生成相应的工单。", 
                     "确认分解", 
                     System.Windows.MessageBoxButton.YesNo, 
                     System.Windows.MessageBoxImage.Question);

                if (result == System.Windows.MessageBoxResult.Yes)
                {
                    // 调用分解API
                    var apiResult = await _productPlanService.DismantleProductPlanAsync(productPlan.Id);

                                         if (apiResult.IsSuc)
                     {
                         System.Windows.MessageBox.Show("生产计划分解成功！", "成功", 
                             System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                         
                         // 刷新数据
                         await SearchProductPlanAsync();
                     }
                     else
                     {
                         // 提供更友好的错误提示
                         string errorMessage = apiResult.msg;
                         if (errorMessage.Contains("NullReferenceException"))
                         {
                             errorMessage = "分解失败：生产计划数据不完整或已损坏，请联系管理员检查数据完整性。";
                         }
                         else if (errorMessage.Contains("InternalServerError"))
                         {
                             errorMessage = "分解失败：服务器内部错误，请稍后重试或联系管理员。";
                         }
                         
                         System.Windows.MessageBox.Show(errorMessage, "错误", 
                             System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                     }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"分解生产计划失败: {ex.Message}", "错误", 
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        #endregion
    }
}
